<script setup lang="ts">
import {h, ref} from 'vue';
import {Button, message, Modal as AntModal, Space, Tag} from 'ant-design-vue';
import {Page} from '#/components/common-ui';
import {BasicIcon} from '#/components/shadcn-ui';
import {useModal, useVxeGrid} from '#/ui-kit';
import {useDictStore} from '#/stores';

import {findMenuListTree, removeMenuInfo} from '#/api/system/menu';

import MenuChangeModal from './menu-change-modal.vue';

const gridExpand = ref(false);

const {getDictData} = useDictStore();

const [Grid, gridApi] = useVxeGrid({
  tableTitle: '菜单列表',
  gridOptions: {
    columns: [
      {fixed: 'left', treeNode: true, field: 'title', title: '菜单名称', minWidth: 120,},
      {
        slots: {
          default: ({row}) => {
            return h(BasicIcon, {class: 'mx-auto', icon: row.icon});
          }
        }, title: '图标', minWidth: 80,
      },
      {field: 'authority', title: '权限标识', minWidth: 120,},
      {field: 'component', title: '组件', minWidth: 250},
      {field: 'sort', title: '排序', minWidth: 80,},
      {
        slots: {
          default: ({row}) => {
            const data = getDictData('enable_status', true).find((item) => item.value === row.enableStatus);
            return h(Tag, {color: data?.color || 'default'}, () => data?.label || '未知');
          }
        }, title: '启用状态', minWidth: 80,
      },
      {field: 'createTime', title: '创建时间', formatter: 'formatDateTime', minWidth: 180,},
      {fixed: 'right', slots: {default: 'action'}, title: '操作', minWidth: 180},
    ],
    proxyConfig: {
      ajax: {
        query: async ({}, formValues) => {
          return await getMenuListTree({
            ...formValues
          });
        },
      }
    },
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    height: 'auto',
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
    },
    treeConfig: {
      parentField: 'parentId',
      rowField: 'id',
      transform: false,
      expandAll: gridExpand.value,
    },
  },
  formOptions: {
    commonConfig: {
      componentProps: {
        allowClear: true,
      }
    },
    schema: [
      {
        label: '菜单名称',
        fieldName: 'title',
        component: 'Input',
        componentProps: {
          placeholder: '请输入菜单名称',
        },
      },
      {
        label: '启用状态',
        fieldName: 'enableStatus',
        component: 'Select',
        componentProps: {
          options: getDictData('enable_status', true),
          placeholder: '请选择启用状态',
        },
      },
    ],
    showCollapseButton: false,
  }
});

const [Modal, modalApi] = useModal({
  class: 'w-[850px]',
  connectedComponent: MenuChangeModal,
})

const getMenuListTree = (params) => {
  gridExpand.value = false;
  return new Promise<{ items: any }>((resolve) => {
    findMenuListTree(params).then(res => {
      resolve({
        items: res,
      });
    }).catch(() => {
      resolve({
        items: [],
      });
    })
  });
};

const handleCreateMenu = (row) => {
  modalApi.setState({title: '新增菜单'});
  if (row) {
    modalApi.setData({parentId: row.id});
  } else {
    modalApi.setData({parentId: 0});
  }
  modalApi.open();
}

const handleUpdateMenu = (row) => {
  modalApi.setState({title: '更新菜单'});
  modalApi.setData(row);
  modalApi.open();
}

const handleRemoveMenu = (row) => {
  AntModal.confirm({
    title: '提示',
    content: '是否删除当前菜单',
    centered: true,
    async onOk() {
      await removeMenuInfo(row.id).then(() => {
        gridApi.reload();
        message.success('菜单删除成功');
      })
    }
  });
}

const handleGridExpand = () => {
  gridExpand.value = !gridExpand.value;
  gridApi.grid?.setAllTreeExpand(gridExpand.value);
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Space>
          <Button type="primary" v-access:code="['sys:menu:create']" @click="handleCreateMenu()">新增菜单</Button>
          <Button @click="handleGridExpand()">{{ gridExpand ? '收起' : '展开' }}</Button>
        </Space>
      </template>

      <template #action="{row}">
        <Button type="link" size="small" v-access:code="['sys:menu:create']" @click="handleCreateMenu(row)">新增
        </Button>
        <Button type="link" size="small" v-access:code="['sys:menu:update']" @click="handleUpdateMenu(row)">编辑
        </Button>
        <Button type="link" size="small" v-access:code="['sys:menu:remove']" @click="handleRemoveMenu(row)">删除
        </Button>
      </template>
    </Grid>

    <Modal @close="() => gridApi.reload()"/>
  </Page>
</template>